package com.soul.common.utils;

import org.springframework.util.ObjectUtils;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

/**
 * 排序工具类
 * @author shiwenshuai
 * @version 1.0
 * @date 2022/11/22 13:58
 */
public class SortUtil {

    /**
     * 排序，根据比较器排序
     * @param sortList
     * @param comparator
     * @param <T>
     */
    public static <T> void sort(List<T> sortList,Comparator<T> comparator){
        if (!ObjectUtils.isEmpty(sortList)){
            sortList.sort(comparator);
        }
    }

    /**
     * 自然排序
     * @param sortList
     * @param fun
     * @param <T>
     */
    public static <T> void sort(List<T> sortList, Function<T, Comparable> fun){
        Comparator<T> comparing = Comparator.comparing(fun, Comparator.nullsLast(Comparator.naturalOrder()));
        sort(sortList,comparing);
    }
    /**
     * 自然排序,根据多个字段
     * @param sortList
     * @param fun1
     * @param fun2s
     * @param <T>
     */
    @SafeVarargs
    public static <T> void sort(List<T> sortList, Function<T, Comparable> fun1, Function<T, Comparable> ...fun2s){
        Comparator<T> comparing = Comparator.comparing(fun1, Comparator.nullsLast(Comparator.naturalOrder()));
        for (Function<T, Comparable> fun : fun2s) {
            comparing = comparing.thenComparing(fun,Comparator.nullsLast(Comparator.naturalOrder()));
        }
        sort(sortList,comparing);
    }
    /**
     * 自然倒序排序
     * @param sortList
     * @param fun
     * @param <T>
     */
    public static <T> void sortDesc(List<T> sortList, Function<T, Comparable> fun){
        Comparator<T> comparing = Comparator.comparing(fun, Comparator.nullsLast(Comparator.reverseOrder()));
        sort(sortList,comparing);
    }
    /**
     * 自然倒序排序,根据多个字段
     * @param sortList
     * @param fun1
     * @param fun2s
     * @param <T>
     */
    @SafeVarargs
    public static <T> void sortDesc(List<T> sortList, Function<T, Comparable> fun1, Function<T, Comparable> ...fun2s){
        Comparator<T> comparing = Comparator.comparing(fun1, Comparator.nullsLast(Comparator.reverseOrder()));
        for (Function<T, Comparable> fun : fun2s) {
            comparing = comparing.thenComparing(fun,Comparator.nullsLast(Comparator.reverseOrder()));
        }
        sort(sortList,comparing);
    }

}
